<?php

namespace App\Http\Service;

use App\Http\Util\Result;
use App\Model\OrderList;
use App\Model\OrderNote;
use App\Model\PromoteDerate;
use App\Model\PromoteGive;
use App\Model\TempReceiver;
use App\Http\Util\OrderStatus;
use Illuminate\Support\Facades\DB;

trait ServiceOrderList{

    /**
     * czs
     * @return mixed
     * 订单列表
     */
    public static function orderList($orderNum,$status,$limit){
        $model = DB::table('order_lists as a')->where('status','<>',9);
        if (!empty($orderNum)) {
            $model->where("a.order_num",'like','%'.$orderNum.'%');
        }
        if (!empty($status)) {
            $model->where("a.status",$status);
        }
        $list = $model
            ->leftJoin('receivers as b','a.receiver_id','=','b.id')
            ->orderBy('a.id','desc')
            ->select("a.*",'b.name')
            ->paginate($limit);
        return Result::success()->setData($list);
    }
    /**
     * czs
     * @return mixed
     * 活动列表
     */
    public static function getList($keyWord,$limit){
        if (empty($keyWord)) {
            $list = Promotion::paginate($limit);
        } else {
            $list = Promotion::where("name","like", '%'.$keyWord.'%')->paginate($limit);
        }
        return Result::success()->setData($list);
    }

    /**
     *后台获取单个id记录
     * czs
     */
    public static function oneOrder($id) {
        $model = DB::table('order_lists as a');
        $res = $model
            ->where("a.id", $id)
            ->leftJoin('members as c','c.id','=','a.member_id')
            ->leftJoin('temp_receivers as f','f.order_id','=','a.id')
            ->leftJoin('order_waybills as h','h.order_id','=','a.id')
            ->leftJoin('post_companies as g','h.company_id','=','g.id')
            ->select("a.*",'c.nickname','f.name as tname','f.address as taddress',
                'f.phone as tphone','f.post_code','g.name as gname','h.waybill')
            ->first();
        return Result::success()->setData($res);
    }

    /**
     * wap获取单个记录
     * czs
     */
    public static function wapForPay($id) {
        $model = DB::table('order_lists as a');
        $res = $model
            ->where("a.id", $id)
            ->leftJoin('members as c','c.id','=','a.member_id')
            ->leftJoin('temp_receivers as f','f.order_id','=','a.id')
            ->leftJoin('order_waybills as h','h.order_id','=','a.id')
            ->leftJoin('post_companies as g','h.company_id','=','g.id')
            ->select("a.*",'c.nickname','f.name as tname','f.address as taddress',
                'f.phone as tphone','f.post_code','g.name as gname','h.waybill','g.code')
            ->first();
        return Result::success()->setData($res);
    }

    /**
     * wap获取单个记录
     * czs
     */
    public static function wapForDelive($id) {
        $model = DB::table('order_lists as a');
        $res = $model
            ->where("a.id", $id)
            ->leftJoin('members as c','c.id','=','a.member_id')
            ->leftJoin('temp_receivers as f','f.order_id','=','a.id')
            ->leftJoin('order_waybills as h','h.order_id','=','a.id')
            ->leftJoin('post_companies as g','h.company_id','=','g.id')
            ->select("a.*",'c.nickname','f.name as tname','f.address as taddress',
                'f.phone as tphone','f.post_code','g.name as gname','h.waybill')
            ->first();
        return Result::success()->setData($res);
    }

    /**
     *更新收货信息
     * czs
     */
    public static function updateReceiver($input, $id) {
        $note['order_id'] = $id;
        $note['note'] = $input['note'];
        $note['status'] = 1;
        $data['receiver'] = $input['name'];
        $data['address'] = $input['address'];
        $data['phone'] = $input['phone'];
        DB::beginTransaction();
        try {
            $sea = OrderNote::where('order_id',$id)->where('status',1)->count();
            if (empty($sea)) {
                OrderNote::create($note);
            } else {
                OrderNote::where('order_id',$id)->where('status',1)->update(['note'=>$note['note']]);
            }
            OrderList::where('id',$id)->update($data);
            DB::commit();
        } catch (Exception $e){
            DB::rollback();
            throw $e;
        }
        return Result::success();
    }

    /**
     * 后台更改价格
     * czs
     */
    public static function updatePrice($price, $id) {
        $numeric = '01234567890123456789';
        OrderList::where('id',$id)->update(['total_price'=>$price,'order_modify_num'=>substr(str_shuffle($numeric),0,16)]);
        return Result::success();
    }

    /**
     * web提交订单
     * czs
     */
    public static function submitOrder($postData,$memberId) {
        if (empty($memberId)) {
            return Result::failure()->setData(1);
        }
        $product = DB::table('products as a')
            ->where('a.id',$postData['id'])
            ->leftJoin('promotions as b','b.id','=','a.promotion_id')
            ->select('a.limit_num','a.inventory')
            ->first();
        if (!empty($product->limit_num)&&$postData['num']>$product->limit_num) {
            return Result::failure()->setMsg("单次最多购买".$product->limit_num."件！");
        }
        if ($postData['num']>$product->inventory) {
            return Result::failure()->setMsg("库存不足！");
        }
        $data1['member_id'] = $memberId;
        $data2['product_id'] = $postData['id'];
        $data2['num'] = $postData['num'];
        $data2['price'] = $postData['price'];
        $data2['one_price'] = $postData['one_price'];
        if (!empty($postData['one_discount'])) {
            $data2['one_discount'] = $postData['one_discount'];
        }
        $data1['status'] = OrderStatus::PREPARE;
        $data1['site'] = \App\Http\Util\Site::WEB;
        $model = DB::table('order_lists');
        $model2 = DB::table('order_details');
        $sel = $model->where('member_id',$data1['member_id'])
            ->where('site',\App\Http\Util\Site::WEB)
            ->where('status',OrderStatus::PREPARE);
        if ($sel->count()) {
            $delId = $sel->pluck('id');
            $sel->delete();
            $model2->where('order_id',$delId)->delete();
        }
        $orderId = $model->insertGetId($data1);
        if ($orderId) {
            $data2['order_id'] = $orderId;
            $model2->insert($data2);
        }
        return Result::success();
    }


    /**
     * 准备订单
     * czs
     */
    public static function prepareOrder($memberId) {
        $model = DB::table('order_lists as a')
            ->where('a.member_id',$memberId)
            ->where('a.status',\App\Http\Util\OrderStatus::PREPARE)
            ->where('a.site',\App\Http\Util\Site::WEB);
        $list = $model
            ->leftJoin('order_details as x','x.order_id','=','a.id')
            ->leftJoin('products as b','b.id','=','x.product_id')
            ->leftJoin('promotions as c','c.id','=','b.promotion_id')
            ->leftJoin('categories as e','e.id','=','b.category_id')
            ->select('a.*','x.order_id','x.product_id','x.num','x.price','b.price as bprice','c.discount','b.name','e.category','c.is_derate','c.is_give')
            ->get();
        return Result::success()->setData($list[0]);
    }


    /**
     * 最终订单
     * czs
     */
    public static function finalOrder($input,$memberId) {
        $model = DB::table('order_lists')
            ->where('member_id',$memberId)
            ->where('status',\App\Http\Util\OrderStatus::PREPARE)
            ->where('site',\App\Http\Util\Site::WEB);
        $receiver = DB::table('receivers')->where('id',$input['receiverId'])->first();
        $numeric = '01234567890123456789';
        $data['order_num'] = substr(str_shuffle($numeric),0,16);
        $data['receiver'] = $receiver->name;
        $data['phone'] = $receiver->phone;
        $data['province'] = $receiver->province;
        $data['city'] = $receiver->city;
        $data['address'] = $receiver->address;
        $data['status'] = \App\Http\Util\OrderStatus::ORDER;
        $data['promote_type'] = !empty($input['promoteType'])?$input['promoteType']:0;
        $data['order_time'] = time();
        $order = self::prepareOrder($memberId)->getData();
        if ($data['promote_type']==1&&$order->is_derate==1) {
            $derate = PromoteDerate::get();
            $effect = 0;
            $cheap = 0;
            foreach ($derate as $v) {
                if ($order->price*$order->num>=$v->effect_amount) {
                    if ($v->effect_amount>=$effect) {
                        $effect = $v->effect_amount;
                        $cheap = $v->cheap_amount;
                    }
                }
            }
            $data['total_price'] = $order->price*$order->num-$cheap;
        } elseif ($data['promote_type']==2&&$order->is_give==1) {
            $give = PromoteGive::get();
            $effect2 = 0;
            $num = 0;
            foreach ($give as $v) {
                if ($order->price*$order->num>=$v->effect_amount) {
                    if ($v->effect_amount>=$effect2) {
                        $effect2 = $v->effect_amount;
                        $num = $v->num;
                    }
                }
            }
            $data['total_price'] = $order->price*$order->num;
            $data['card_num'] = $num;
        } else {
            $data['total_price'] = $order->price*$order->num;
        }
        $res = $model->update($data);
        DB::table('products')->where('id',$order->product_id)->decrement('inventory', $order->num);
        return Result::success()->setData($res);
    }

    /**
     * web所有订单
     * czs
     */
    public static function allOrder($memberId,$limit) {
        $model = DB::table('order_lists as a')
            ->where('a.member_id',$memberId)
            ->where('a.status','<>',\App\Http\Util\OrderStatus::PREPARE)
            ->orderBy('id','desc');
        $list['count'] = $model->count();
        $list['list'] = $model
            ->select('a.*')
            ->paginate($limit);
        return Result::success()->setData($list);
    }

    /**
     * wap所有订单
     * czs
     */
    public static function wapAllOrder($memberId,$limit) {
        $model = DB::table('order_lists as a')
            ->where('a.member_id',$memberId)
            ->where('a.status','<>',\App\Http\Util\OrderStatus::PREPARE)
            ->orderBy('id','desc');
        $list = $model
            ->select('a.*')
            ->paginate($limit);
        return Result::success()->setData($list);
    }

    /**
     * web删除过期未付款订单
     * czs
     */
    public static function deleteDue($memberId) {
        $list = DB::table('order_lists as a')
            ->where('a.member_id',$memberId)
            ->where('a.status',1)
            ->get();
        foreach ($list as $v) {
            $orderTime = $v->order_time;
            $timeLength = DB::table('order_settings')->pluck('due_time_length');
            if ((time()-$orderTime)>$timeLength*60) {
                $orderDetail = DB::table('order_details')->where('order_id',$v->id)->first();
                DB::table('products')->where('id',$orderDetail->product_id)->increment('inventory', $orderDetail->num);
                DB::table('order_details')->where('order_id',$v->id)->delete();
                DB::table('order_lists')->where('id',$v->id)->delete();
            }
        }
    }

    /**
     * web等待付款
     * czs
     */
    public static function forPay($memberId,$limit) {
        $model = DB::table('order_lists as a')
            ->where('a.member_id',$memberId)
            ->where('a.status',\App\Http\Util\OrderStatus::ORDER)
            ->orderBy('order_time','desc');
        $list['count'] = $model->count();
        $list['list'] = $model
            ->select('a.*')
            ->paginate($limit);
        return Result::success()->setData($list);
    }
    /**
     * web等待付款
     * czs
     */
    public static function wapForPayList($memberId,$limit) {
        $model = DB::table('order_lists as a')
            ->where('a.member_id',$memberId)
            ->where('a.status',\App\Http\Util\OrderStatus::ORDER)
            ->orderBy('order_time','desc');
        $list = $model
            ->select('a.*')
            ->paginate($limit);
        return Result::success()->setData($list);
    }

    /**
     * web待发货
     * czs
     */
    public static function forDelive($memberId,$limit) {
        $model = DB::table('order_lists as a')
            ->where('a.member_id',$memberId)
            ->where('a.status',\App\Http\Util\OrderStatus::DELIVE)
            ->orderBy('pay_time','desc');
        $list['count'] = $model->count();
        $list['list'] = $model
            ->select('a.*')
            ->paginate($limit);
        return Result::success()->setData($list);
    }

    /**
     * wap待发货
     * czs
     */
    public static function wapForDeliveList($memberId,$limit) {
        $model = DB::table('order_lists as a')
            ->where('a.member_id',$memberId)
            ->where('a.status',\App\Http\Util\OrderStatus::DELIVE)
            ->orderBy('pay_time','desc');
        $list = $model
            ->select('a.*')
            ->paginate($limit);
        return Result::success()->setData($list);
    }

    /**
     * web待收货
     * czs
     */
    public static function forReceive($memberId,$limit) {
        $model = DB::table('order_lists as a')
            ->where('a.member_id',$memberId)
            ->where('a.status',\App\Http\Util\OrderStatus::RECEIVE)
            ->orderBy('delive_time','desc');
        $list['count'] = $model->count();
        $list['list'] = $model
            ->select('a.*')
            ->paginate($limit);
        return Result::success()->setData($list);
    }

    /**
     * wap待收货
     * czs
     */
    public static function wapForReceiveList($memberId,$limit) {
        $model = DB::table('order_lists as a')
            ->where('a.member_id',$memberId)
            ->where('a.status',\App\Http\Util\OrderStatus::RECEIVE)
            ->orderBy('delive_time','desc');
        $list = $model
            ->select('a.*')
            ->paginate($limit);
        return Result::success()->setData($list);
    }

    /**
     * 删除订单
     * czs
     */
    public static function deleteOrder($id) {
        $del = DB::table('order_details')->where('order_id',$id)->delete();
        if ($del) {
           $del2 = DB::table('order_lists')->where('id',$id)->delete();
           return Result::success()->setData($del2);
        }
    }

    /**
     * 确认收货
     * czs
     */
    public static function confirmReceive($id) {
        $data['status'] = 4;
        $data['complete_time'] = time();
        $res = DB::table('order_lists')->where('id',$id)->update($data);
        return Result::success()->setData($res);
    }

    /**
     * web在线支付
     * czs
     */
    public static function onlinePay($id) {
        $res = DB::table('order_lists as a')
            ->where('a.id',$id)
            ->select('a.*')
            ->first();
        return Result::success()->setData($res);
    }

    /**
     * wap在线支付
     * czs
     */
    public static function onlineWapPay($id) {
        $res = DB::table('order_lists as a')
            ->where('a.id',$id)
            ->select('a.*')
            ->first();
        return Result::success()->setData($res);
    }

    public static function ajaxCall($id) {
        $sel = DB::table('order_lists')->where('id',$id)->pluck('status');
        return Result::success()->setType($sel);
    }
}


